﻿using System;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MongoDB.Driver;
using Sustainalytics.DataLayer.ConnectionStrings;
using Sustainalytics.DataLayer.Shared;
using Sustainalytics.Entities;
using Sustainalytics.Entities.ConnectionStrings;
using System.Web.Http.Cors;

namespace Sustainalytics.Governance.Service.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    [RoutePrefix("api/v1/keycgtemplate")]
    public class GovernanceIssueTemplateController:ApiController
    {
        private readonly IRepositoryCollection<GovernanceIndicatorTemplate> _repositoryIndicator; 
        public GovernanceIssueTemplateController()
        {
            var connectionStringsManager =
                ConnectionStringsManager.GetInstance(
                    ConnectionStringsRepository.GetInstance(ConfigurationManager.ConnectionStrings["ClientPlatform"].ConnectionString));
            _repositoryIndicator =
                new RepositoryCollection<GovernanceIndicatorTemplate>(
                    connectionStringsManager.GetConnectionString(ConnectionStringType.GovernanceDW));
        }

        [Route()]
        public HttpResponseMessage Get()
        {
            try
            {
                var aggregateData = _repositoryIndicator
                    .Collection()
                    .Aggregate()
                    .Group(x => x.IssueName, x => new { Name = x.First().IssueName, Number = x.First().IssueNumber })
                    .SortBy(x=> x.Number)
                    .ToList();

                return Request.CreateResponse(HttpStatusCode.OK, aggregateData);

            }
            catch (Exception ex)
            {
                GovernanceEventSource.Log.LogError(ex);
                
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "An unhandled exception happened");
            }
        }
    }
}
